//
//  MainViewController.m
//  AllFamily
//
//  Created by chirui on 2018/5/23.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "MainViewController.h"
#import "MyCenterCViewCell.h"
#import "MyCenterCollectionReusableView.h"
#import "SearchView.h"
#import "MessageListViewController.h"
#import "SecondClassViewController.h"
#import "RuleDetailsViewController.h"
#import "SearchViewController.h"
#import "MoreGoodsViewController.h"

@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate>
{
    UICollectionView * _collectionView;
    NSDictionary * userDic;
    NSDictionary * dataDic;
    
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    
    NSString * messageCount;
    NSArray * classNavArray;
}

@end

@implementation MainViewController

-(void)viewWillAppear:(BOOL)animated{
    
    if (verifTokenAndEnter) {
        
        [self getMessageCount];
    }else{
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_news" target:self action:@selector(message)];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    _dataArray= @[].mutableCopy;
    TitleView(@"积分商城")
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    self.view.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [self creatCollectionView];
    [self getGoodsListData];
    [self getBannerRequest];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_classification" target:self action:@selector(classClick)];
    
    
    
    
 self.navigationItem.titleView =    [SearchView  creatSearchTextFieldForDelegate:self Placeholder:@"请输入商品名称"];
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    SearchViewController * search = [[SearchViewController alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:search animated:YES];
    NSLog(@"跳转搜索页");
}

-(void)message{
    if (verifTokenAndEnter) {
        MessageListViewController * message = [[MessageListViewController alloc]init];
        message.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:message animated:YES];
    }else{
        LoginAndSignUpVC * login = [[LoginAndSignUpVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        
    }
   
    
}

-(void)classClick{
    
    SecondClassViewController * class =[SecondClassViewController new];
    class.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:class animated:YES];
}


#pragma creatCollectionView

-(void)creatCollectionView {
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SH_TabBarHeight-SH_TopHeight) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        
        _page = 1;
        [self getBannerRequest];
        [self getGoodsListData];
    }];
    _collectionView.mj_header = header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getGoodsListData];
        
    }];
    
    footer.automaticallyRefresh = YES;
    _collectionView.mj_footer =footer;
    
    if (_dataArray.count>10) {
        _collectionView.mj_footer.hidden = NO;
    }else {
        
        _collectionView.mj_footer.hidden = YES;
    }
    
    
    //注册cell类
    [_collectionView registerNib:[UINib nibWithNibName:@"MyCenterCViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCenterCViewCell"];
    
    //    注册header类
    [_collectionView registerClass:[MyCenterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCenterCollectionReusableView"];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.row];
    MyCenterCViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCenterCViewCell" forIndexPath:indexPath];
    cell.clipsToBounds = NO;
    
    UILabel *tagLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 65, 20)];
    tagLabel.font =[UIFont systemFontOfSize:14];
    tagLabel.text =@"公益商品";
    tagLabel.textColor =[UIColor whiteColor];
    tagLabel.backgroundColor =  Color(58, 168, 38);
    [cell.goodsImage addSubview:tagLabel];
    if ([dic[@"is_public"] isEqualToString:@"yes"]) {
        
        tagLabel.hidden = NO;
    }else {
        
         tagLabel.hidden = YES;
    }
    
    [cell.goodsImage sd_setImageWithURL:ImageUrl(dic[@"cover_photo"]) placeholderImage:ImageName(@"img_new_default")];

    cell.gooseName.frame = CGRectMake(6, CGRectGetMaxY(cell.goodsImage.frame)+5, (WIDTH-10)/2-12, 20);
    cell.gooseName.text = dic[@"product_name"];

    cell.gooseName.numberOfLines = 2;
    [cell.gooseName sizeToFit];

    cell.scoreLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"price"]];
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary * Dic = _dataArray[indexPath.row];
    GoodsDetailsViewController * goods =[[GoodsDetailsViewController alloc]init];
    goods.goodsId = [NSString stringWithFormat:@"%@",Dic[@"id"]];
    goods.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goods animated:YES];
    
  
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    第一个参数是宽，第二个参数是高 5s  1.8   6 1.6   6p
    float height;
    if (ISP5||ISP4) {
        height = 1.5;
    }else if (ISP6){
        height = 1.3;
        
    }else if (ISP6P){
        height = 1.4;
    }else {
        
        height = 1.4;
    }
    
    CGSize size=CGSizeMake((WIDTH-10)/2, (WIDTH-10)/2*height);
    
    return size;
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //上 左 下 右
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置水平间隙   默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

////设置垂直间隙  默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(0,760);
}
//设置footer的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    //第一个参数：水平滑动时footer的宽度
    //第二个参数：垂直滑动时footer的高度
    return CGSizeMake(0, 0);
}

//kind:第二个参数:区分组头,组尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        MyCenterCollectionReusableView * heardView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCenterCollectionReusableView" forIndexPath:indexPath];
        heardView.backgroundColor =[UIColor whiteColor];
        
        for (UIView * view in heardView.subviews) {
            
            [view removeFromSuperview];
        }
        
        NSMutableArray  * bannerArray = @[].mutableCopy;
        if (bannerArray) {
            [bannerArray removeAllObjects];
        }
        if (dataDic) {
            
            if ([dataDic[@"banner"] isKindOfClass:[NSArray class]]) {
                for (NSDictionary * dic in dataDic[@"banner"]) {
                    
                    [bannerArray addObject:dic[@"image"]];
                }
                
            }
        }
        
        
        NSArray * loacArray =@[@"banner",@"banner"];
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0, WIDTH, 180) delegate:self placeholderImage:[UIImage imageNamed:@"banner"]];
        cycleScrollView.backgroundColor =Color(229, 229, 229);
        cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        cycleScrollView.currentPageDotColor = NavBackColor;
        [heardView addSubview:cycleScrollView];
//        cycleScrollView.localizationImageNamesGroup = loacArray;
//        if (bannerArray!=nil) {
            cycleScrollView.imageURLStringsGroup = bannerArray;
//        }else{
//            cycleScrollView.localizationImageNamesGroup = loacArray;
//        }
        cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
            
        };

        
        UILabel  * goodsTitle = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(cycleScrollView.frame)+15, 120, 20)];
        goodsTitle.text = @"核心商品";
        goodsTitle.font = [UIFont systemFontOfSize:17];
        [heardView addSubview:goodsTitle];
        
        UIButton * moreBtn  = [UIButton buttonWithType:UIButtonTypeSystem];
        moreBtn.frame =  CGRectMake(WIDTH - 80,CGRectGetMaxY(cycleScrollView.frame)+5, 80, 40);
        [moreBtn setTitle:@"更多>" forState:UIControlStateNormal];
        moreBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [moreBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
        [heardView addSubview:moreBtn];
        
        [self creatViewLineFrame:CGRectMake(10, CGRectGetMaxY(cycleScrollView.frame)+ 17, 2, 16) andColor:NavBackColor andView:heardView];
        
        [self creatViewLineFrame:CGRectMake(0, CGRectGetMaxY(cycleScrollView.frame)+ 50, WIDTH, 1) andColor:[UIColor groupTableViewBackgroundColor] andView:heardView];
        
        
        UIScrollView * scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(cycleScrollView.frame)+ 60, WIDTH, 195)];
        [heardView addSubview:scrollView];
        //边界弹的效果，默认yes
        scrollView.bounces = NO;
        scrollView.backgroundColor = [UIColor whiteColor];
        //关闭水平滑块：默认YES
        scrollView.showsHorizontalScrollIndicator = NO;
        //关闭垂直滑块：默认YES
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = NO;
        //设置代理
        scrollView.delegate = self;
        
        UIView * btnView;
        
        NSArray * goodsArray = dataDic[@"core_product"];
        if (goodsArray.count!=0) {
            for (int i =0; i<goodsArray.count; i++) {
                NSDictionary * dic = goodsArray[i];
                btnView =[[UIView alloc]init];
                btnView.frame = CGRectMake(10 +(15)*i +120*i, 0, 120, 195);
                btnView.backgroundColor =[UIColor whiteColor];
                UIButton * listBtn_one =[UIButton buttonWithType:UIButtonTypeCustom];
                listBtn_one.frame = CGRectMake(0, 0, 120, 120);
                listBtn_one.tag = 1000+i;
                [listBtn_one sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"cover_photo"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"moren_image"]];
                [listBtn_one addTarget:self action:@selector(goodsBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                
                UILabel * nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 130, 120, 20)];
                nameLabel.font =[UIFont systemFontOfSize:14];
                nameLabel.text =dic[@"product_name"];
                nameLabel.numberOfLines =2;
                nameLabel.textColor = RGBa(0x444444);
                [nameLabel sizeToFit];
                
                UILabel *tagLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 65, 20)];
                tagLabel.font =[UIFont systemFontOfSize:14];
                tagLabel.text =@"公益商品";
                tagLabel.textColor =[UIColor whiteColor];
                tagLabel.backgroundColor =  Color(58, 168, 38);
                [listBtn_one addSubview:tagLabel];
                if ([dic[@"is_public"] isEqualToString:@"yes"]) {
                    
                    tagLabel.hidden = NO;
                }else {
                    
                    tagLabel.hidden = YES;
                }
                [btnView addSubview:nameLabel];
                
                UILabel * nowPrice =[[UILabel alloc]initWithFrame:CGRectMake(0, 165, 120, 20)];
                nowPrice.text =[NSString stringWithFormat:@"￥%@",dic[@"price"]];
                nowPrice.textColor =[UIColor redColor];
                nowPrice.font =[UIFont systemFontOfSize:15];
                [btnView addSubview:nowPrice];
           
                [btnView addSubview:listBtn_one];
                [scrollView addSubview:btnView];
                
            }
            
        }
        scrollView.contentSize = CGSizeMake(CGRectGetMaxX(btnView.frame)+10 , 195);
        
        [self creatViewLineFrame:CGRectMake(0, CGRectGetMaxY(scrollView.frame), WIDTH, 10) andColor:[UIColor groupTableViewBackgroundColor] andView:heardView];
        
        UILabel  * helpTitle = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(scrollView.frame)+25, 120, 20)];
        helpTitle.text = @"互助公示";
        helpTitle.font = [UIFont systemFontOfSize:17];
        [heardView addSubview:helpTitle];
        
        [self creatViewLineFrame:CGRectMake(10, CGRectGetMaxY(scrollView.frame)+ 27, 2, 16) andColor:NavBackColor andView:heardView];
        
        UIScrollView * helpScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(helpTitle.frame)+15, WIDTH, 195)];
        helpScrollView.bounces = NO;
        helpScrollView.backgroundColor = [UIColor whiteColor];
        helpScrollView.showsHorizontalScrollIndicator = NO;
        helpScrollView.showsVerticalScrollIndicator = NO;
        helpScrollView.pagingEnabled = NO;
        helpScrollView.delegate = self;
        [heardView addSubview:helpScrollView];
        UIView * helpBtnView;
        NSArray * helpArray = dataDic[@"help"];
        if (helpArray.count!=0) {
  
        for (int i =0; i<helpArray.count; i++) {
            NSDictionary * dic = helpArray[i];
            helpBtnView =[[UIView alloc]init];
            helpBtnView.frame = CGRectMake(10 +(15)*i +140*i, 0, 140, 195);
            helpBtnView.backgroundColor =[UIColor whiteColor];
            UIButton * listBtn_one =[UIButton buttonWithType:UIButtonTypeCustom];
            listBtn_one.frame = CGRectMake(0, 0, 140, 140);
            listBtn_one.tag = 100+i;
            [listBtn_one sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"cover_photo"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"moren_image"]];
           [listBtn_one addTarget:self action:@selector(helpBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            
            UILabel * nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 150, 140, 20)];
            nameLabel.font =[UIFont systemFontOfSize:14];
            nameLabel.text =dic[@"title"];
            nameLabel.numberOfLines =2;
            nameLabel.textColor = RGBa(0x333333);
            [nameLabel sizeToFit];
            
            [helpBtnView addSubview:nameLabel];
            [helpBtnView addSubview:listBtn_one];
            [helpScrollView addSubview:helpBtnView];
            
         }
        }
         helpScrollView.contentSize = CGSizeMake(CGRectGetMaxX(helpBtnView.frame)+10 , 195);
        
        [self creatViewLineFrame:CGRectMake(0, CGRectGetMaxY(helpScrollView.frame), WIDTH, 10) andColor:[UIColor groupTableViewBackgroundColor] andView:heardView];
        
        UILabel * hotLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(helpScrollView.frame)+10, WIDTH, 50)];
        hotLabel.text = @"热门推荐";
        hotLabel.textAlignment = NSTextAlignmentCenter;
        hotLabel.font = [UIFont systemFontOfSize:17];
        [heardView addSubview:hotLabel];
        
        return heardView;
    }else{
        
        return nil;
    }
}

-(void)goodsBtnClick:(UIButton *)btn{
    
    NSArray * goodsArray = dataDic[@"core_product"];
    NSDictionary * Dic = goodsArray[btn.tag - 1000];
    GoodsDetailsViewController * goods =[[GoodsDetailsViewController alloc]init];
    goods.goodsId = [NSString stringWithFormat:@"%@",Dic[@"id"]];
    goods.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goods animated:YES];
    
}

-(void)helpBtnClick:(UIButton *)btn{
    
    NSDictionary * dic = dataDic[@"help"][btn.tag - 100];
    
    RuleDetailsViewController * rule = [[RuleDetailsViewController alloc]init];
    rule.hidesBottomBarWhenPushed = YES;
    rule.url = dic[@"web_url"];
    [self.navigationController pushViewController:rule animated:YES];
    
}

-(void)moreBtnClick{
    
    MoreGoodsViewController * more =[[MoreGoodsViewController alloc]init];
    more.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:more animated:YES];
}

-(void)creatViewLineFrame:(CGRect)frame andColor:(UIColor *)col andView:(UIView *)view{
   
    UIView * orgView  =[[UIView alloc]initWithFrame:frame];
    orgView.backgroundColor = col;
    [view addSubview:orgView];
}

-(void)getGoodsListData{


    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_collectionView.mj_footer setState: MJRefreshStateNoMoreData];

            return ;
        }
    }
    NSDictionary * dic = @{
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10"

                           };

    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_mainList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            if (_page==1) {

                if (_dataArray) {

                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {

                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {

                        [_dataArray addObject:dic];
                    }
                }
            }else {

                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {

                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {

                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{


                if (_dataArray.count>0) {
                    if (_dataArray.count<10) {

                        _collectionView.mj_footer.hidden = YES;
                    }
                }else {
                    _collectionView.mj_footer.hidden = YES;

                }
                [_collectionView.mj_header endRefreshing];
                [_collectionView.mj_footer endRefreshing];
                [_collectionView reloadData];

            });

        }else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];

        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];

}

-(void)getMessageCount{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")};
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(noRead_messageCount_api) andparameters:dic Success:^(id responseObject) {
        
        if (codeSucess) {
            
            messageCount = responseObject[@"datas"][@"count"];
            
            if ([messageCount isEqualToString:@"0"]) {
                
                  self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_news" target:self action:@selector(message)];
            }else{
                
                 self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_news_pre" target:self action:@selector(message)];
            }
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
      
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

-(void)getBannerRequest{
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_bannerData_api) andparameters:nil Success:^(id responseObject) {
        
        if (codeSucess) {
            
            dataDic = responseObject[@"datas"];
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        [_collectionView reloadData];

    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}


@end
